<?php

/**
* Directory handler.
* 
*/
abstract class Kernel_Util_Directory
{
    
    /**
    * Copy source to the target.
    * 
    * @param string $source
    * @param string $target
    * @param array $skip_list 
    * @return boolean
    */
    static public function copy($source, $target, array $skip_list = array()) 
    {
        array_unshift($skip_list, '.', '..');
        $source = rtrim($source, '/');
        
        if (is_dir($source) && !in_array($source, $skip_list))
        {
            mkdir($target, 0707);
            
            $handler = dir($source);
            
            while (false !== ($file = $handler->read())) {
                if (in_array($file, $skip_list)) { continue; }
                
                $source_entry = $source . '/' . $file;
                $target_entry = $target . '/' . $file;
                if (is_dir($source_entry)) {
                    self::copy($source_entry, $target_entry, $skip_list);
                    continue;
                }
                copy($source_entry, $target_entry);
            }
            
            $handler->close();
        }
        elseif (is_file($source)) 
        {
            copy($source, $target);
        }
        else 
        {
            return false;
        }
        
        return true;
    }
    
    /**
    * Delete specified directory.
    * 
    * @param string $dir
    * @return boolean
    */
    static public function delete($dir) 
    {
        if (!is_dir($dir)) { return false; }
        
        self::clear($dir);
        return rmdir($dir);
    }
    
     /**
    * Clear specified directory
    * 
    * @param string $dir
    */
    static public function clear($dir) 
    {
        if (!is_dir($dir)) { return; }
        $dir = rtrim($dir, '/');
        
        
        $handler = dir($dir);
        
        while (false !== ($file = $handler->read())) {
            if ($file == '.' || $file == '..') { continue; }
            
            is_dir($entry = $dir . '/' . $file) ? self::clear($entry) : @unlink($entry);
        }
        
        $handler->close();
    }
    
}